package cn.lizemin.demo.clone;

/**
 * @author: lizemin
 * @version: 1.0
 */
public class Person implements Cloneable{
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //首先通过父类克隆基本数据类型
        Object obj = super.clone();
        //向下转换类型
        Person person = (Person)obj;
        //手工对引用类型进行复制,这里克隆引用数据前，也需要重写Dog类中的clone方法，否则这里不能调用clone方法
        Dog dog = (Dog) person.getDog().clone();
        //再传参数
        person.setDog(dog);
        return person;

    }

    //这是一个main方法,是程序的入口
    public static void main(String[] args) throws CloneNotSupportedException {
        test1();

    }

    private static void test1() throws CloneNotSupportedException {
        Dog putty = new Dog("putty", 2);
        Person person = new Person("lizemin",23,putty);
        //克隆person
        Person person2 = (Person)person.clone();
        Dog dog = person.getDog();
        Dog dog2 = person2.getDog();

        //结果，两个地址完全相同
        System.out.println(dog);
        System.out.println(dog2);

    }


    private String lastName ; //
    private Integer age;
    //引用类型数据
    private Dog dog;

    public Person(String lastName, Integer age, Dog dog) {
        this.lastName = lastName;
        this.age = age;
        this.dog = dog;
    }

    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }

    public Dog getDog() {
        return dog;
    }
    public void setDog(Dog dog) {
        this.dog = dog;
    }
    @Override
    public String toString() {
        return "Person{" +
                "lastName='" + lastName + '\'' +
                ", age=" + age +
                ", dog=" + dog +
                '}';
    }

    public Person() {
    }
}
